<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="员工姓名" prop="realName">
                <el-input
                    v-model="queryParams.realName"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="工号" prop="staffNum">
                <el-input
                    v-model="queryParams.staffNum"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="部门" prop="deptName">
                <treeselect
                    v-model="queryParams.deptId"
                    :options="deptOptions"
                    :show-count="true"
                    placeholder=""
                    @keyup.enter.native="handleQuery"
                    style="width: 215px"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['back:leave:add']"
                        >新建</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="leaveList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    type="index"
                    label="序号"
                    width="55"
                    align="center"
                />
                <el-table-column label="姓名" align="center" prop="realName" />
                <el-table-column label="工号" align="center" prop="staffNum" />
                <el-table-column label="性别" align="center" prop="sex">
                    <template slot-scope="scope">
                        <dict-tag
                            v-if="scope.row.sex || scope.row.sex == 0"
                            :options="dict.type.sys_user_sex"
                            :value="scope.row.sex"
                        />
                        <span v-else>—</span>
                    </template></el-table-column
                >

                <el-table-column label="部门" align="center" prop="deptId">
                    <template slot-scope="scope">
                        <span>{{ parseSelectTree(scope.row.deptId) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="岗位" align="center" prop="postId">
                    <template slot-scope="scope">
                        <span>{{ parsePostName(scope.row.postId) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                  label="0:请假，1：加班"
                  align="center"
                  prop="type"
              /> -->
                <el-table-column
                    label="请假时间"
                    align="center"
                    prop="toTime"
                    width="180"
                >
                    <template slot-scope="scope">
                        <span>{{
                            parseTime(scope.row.toTime, "{y}-{m}-{d}")
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="请假时长（小时）"
                    align="center"
                    prop="timeVal"
                />
                <!-- <el-table-column label="请假原因（备注）" align="center" prop="remark" /> -->
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['back:leave:edit']"
                            >修改</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleRead(scope.row)"
                            v-hasPermi="['back:leave:edit']"
                            >查看</el-button
                        >
                        <el-button
                            style="color: red"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['back:leave:remove']"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改【请填写功能名称】对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="140px"
                >
                    <el-form-item
                        label="姓名"
                        :prop="showOptions || form.id ? '' : 'realName'"
                    >
                        <el-input
                            suffix-icon="el-icon-search"
                            readonly
                            @focus="showTableDialog"
                            v-model="form.realName"
                            placeholder=""
                            :disabled="showOptions || this.form.id"
                        />
                    </el-form-item>

                    <el-form-item
                        label="部门"
                        :prop="showOptions || form.id ? '' : 'deptId'"
                    >
                        <treeselect
                            v-model="form.deptId"
                            :options="deptOptions"
                            :show-count="true"
                            placeholder=""
                            disabled
                        />
                    </el-form-item>

                    <el-form-item
                        label="岗位"
                        :prop="showOptions || form.id ? '' : 'postId'"
                    >
                        <el-select
                            disabled
                            v-model="form.postId"
                            placeholder=""
                            clearable
                        >
                            <el-option
                                v-for="item in postList"
                                :key="item.postId"
                                :label="item.postName"
                                :value="item.postId"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item
                        label="请假日期"
                        :prop="showOptions ? '' : 'toTime'"
                    >
                        <el-date-picker
                            clearable
                            v-model="form.toTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder=""
                            :disabled="showOptions"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item
                        label="请假时长"
                        prop="timeVal"
                        v-if="$store.getters.allDefectObj['HR-WEB-068'] == 1"
                        :rules="
                            showOptions
                                ? []
                                : [
                                      {
                                          required: true,
                                          message: '请假时长不能为空',
                                          trigger: 'blur',
                                      },
                                      {
                                          pattern: /^[1-9]\d*$/,
                                          message: '请假时长必须为正整数',
                                          trigger: 'blur',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            v-model="form.timeVal"
                            placeholder=""
                            :disabled="showOptions"
                        />
                    </el-form-item>
                    <el-form-item
                        label="请假时长"
                        v-else
                        prop="timeVal"
                        :rules="
                            showOptions
                                ? []
                                : [
                                      {
                                          required: true,
                                          message: '请假时长不能为空',
                                          trigger: 'blur',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            v-model="form.timeVal"
                            placeholder=""
                            :disabled="showOptions"
                        />
                    </el-form-item>
                    <el-form-item
                        label="请假原因（备注）"
                        prop="remark"
                        v-if="$store.getters.allDefectObj['HR-WEB-067'] == 0"
                    >
                        <el-input
                            v-model="form.remark"
                            type="textarea"
                            :rows="5"
                            placeholder=""
                            :disabled="showOptions"
                        />
                    </el-form-item>
                    <el-form-item
                        v-else
                        label="请假原因（备注）"
                        prop="remark"
                        :rules="[
                            {
                                max: 100,
                                message: '请假原因（备注）长度不超过100个字符',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input
                            v-model="form.remark"
                            type="textarea"
                            :rows="5"
                            placeholder=""
                            :disabled="showOptions"
                        />
                    </el-form-item>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button
                    type="primary"
                    @click="submitForm"
                    v-show="!showOptions"
                    >保 存</el-button
                >
                <el-button @click="cancel">返 回</el-button>
            </div>
        </el-dialog>
        <!-- <table-dialog :open.sync="showTableVision"   @confirm="setFormBase">
        </table-dialog> -->
        <userTableDialog
            title="选择员工"
            :defaultParams="defaultParams"
            :open.sync="showTableVision"
            @confirm="setFormBase"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listLeave,
    getLeave,
    delLeave,
    addLeave,
    updateLeave,
} from "@/api/back/leave";

import tableDialog from "../tableDialog.vue";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";
export default {
    name: "Leave",
    dicts: ["sys_user_sex"],
    data() {
        return {
            // 职位选项
            postList: [],
            // 部门树选项
            deptOptions: [],
            deptOptionsArray: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 【请填写功能名称】表格数据
            leaveList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                staffNum: null,
                pageNum: 1,
                pageSize: 10,

                realName: null,
                sex: null,
                staffType: null,
                userId: null,
                deptId: null,
                orgId: null,
                postId: null,
                type: 0,
                toTime: null,
                timeVal: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                realName: [
                    {
                        required: true,
                        message: "姓名不能为空",
                        trigger: "change",
                    },
                ],
                userId: [
                    {
                        required: true,
                        message: "用户ID不能为空",
                        trigger: "blur",
                    },
                ],
                // deptId: [
                //     {
                //         required: true,
                //         message: "部门ID不能为空",
                //         trigger: "blur",
                //     },
                // ],
                // orgId: [
                //     {
                //         required: true,
                //         message: "部门不能为空",
                //         trigger: "blur",
                //     },
                // ],
                // postId: [
                //     {
                //         required: true,
                //         message: "所属岗位的ID字符串不能为空",
                //         trigger: "blur",
                //     },
                // ],
                type: [
                    {
                        required: true,
                        message: "0:请假，1：加班不能为空",
                        trigger: "change",
                    },
                ],
                toTime: [
                    {
                        required: true,
                        message: "请假不能为空",
                        trigger: "change",
                    },
                ],
                timeVal: [],
            },

            showTableVision: false,
            showOptions: false,
            defaultParams: {
                isLink: true,
                staffTypes:
                    this.$store.getters.allDefectObj["HR-WEB-065"] == 1
                        ? "1,4"
                        : "1,2,3,4",
            },
        };
    },
    components: { tableDialog, Treeselect },
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
    },
    methods: {
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let nameArr = [];
                let selIds = ids.split(",");
                this.postList.forEach((item) => {
                    selIds.forEach((sel) => {
                        if (item.postId == sel) {
                            nameArr.push(item.postName);
                        }
                    });
                });
                if (nameArr.length <= 0) {
                    return "—";
                }
                return nameArr.join(",");
            }
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        setFormBase(row) {
            let temp = { ...row };
            console.log(temp, "temp");
            // 带入姓名 用户id  部门id 部门 所属岗位
            this.form.deptId = temp.deptId;
            this.form.userId = temp.userId;
            this.form.orgId = temp.orgId;
            this.form.staffNum = temp.staffNum;
            this.form.postId = Number(temp.postId);

            this.form.sex = temp.sex;
            this.form.staffType = temp.staffType;

            this.form.type = "0";
            this.$set(this.form, "realName", temp.realName);
        },
        showTableDialog() {
            this.showTableVision = true;
        },
        /** 查询【请填写功能名称】列表 */
        getList() {
            this.loading = true;
            listLeave(this.queryParams).then((response) => {
                this.leaveList = response.rows;
                console.log(this.leaveList, "this.leaveList");
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                realName: null,
                sex: null,
                staffType: null,
                userId: null,
                deptId: null,
                orgId: null,
                postId: null,
                type: null,
                toTime: null,
                timeVal: null,
                remark: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.deptId = null;
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新建按钮操作 */
        handleAdd() {
            this.reset();
            this.showOptions = false;
            this.open = true;
            this.title = "请假登记";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getLeave(id).then((response) => {
                this.form = response.data;
                if (this.form.postId) {
                    this.form.postId = Number(this.form.postId);
                }
                this.showOptions = false;
                this.open = true;
                this.title = "请假编辑";
            });
        },
        /** 查看按钮操作 */
        handleRead(row) {
            this.reset();
            const id = row.id || this.ids;
            getLeave(id).then((response) => {
                this.form = response.data;
                // if (this.form.postId) {
                //     let tempList = this.form.postId.split(",");
                //     this.form.postId = [];

                //     tempList.forEach((item) => {
                //         this.form.postId.push(Number(item));
                //     });
                // }

                this.form.postId = Number(this.form.postId);
                if (!this.form.remark) {
                    this.form.remark = "—";
                }

                this.showOptions = true;
                this.open = true;
                this.title = "请假查看";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.postId.length > 0) {
                        this.form.postId = this.form.postId.join(",");
                    }
                    if (this.form.remark && this.form.remark.length > 100) {
                        return;
                    }
                    if (
                        this.form.timeVal &&
                        /^[1-9]\d*$/.test(this.form.timeVal) == false
                    ) {
                        return;
                    }

                    if (this.form.id != null) {
                        updateLeave(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addLeave(this.form).then((response) => {
                            this.$modal.msgSuccess("新建成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm("请确认是否删除该记录", "删除确认")
                .then(function () {
                    return delLeave(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {
                    if (this.$store.getters.allDefectObj["HR-WEB-069"] == 0) {
                        delLeave(ids).then(() => {
                            this.getList();
                            this.$modal.msgSuccess("删除成功");
                        });
                    }
                });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "back/leave/export",
                {
                    ...this.queryParams,
                },
                `leave_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
